package com.yand.redis;

public class Funnel {
    int capacity;//漏斗容量
    double leakingRate;//漏水速度
    int leftQuota;//漏斗剩余的量
    long leakingTs;//上次漏斗漏水的 时间

    public Funnel(int capacity, double leakingRate, int leftQuota, long leakingTs) {
        this.capacity = capacity;
        this.leakingRate = leakingRate;
        this.leftQuota = leftQuota;
        this.leakingTs = leakingTs;
    }


    private void makeSpace(){
        long nowTs = System.currentTimeMillis();
        long deltaTs = nowTs - this.leakingTs;//这个是间隔的时间
        int deltaQuota = (int)(deltaTs*leakingRate);//漏掉的水
        if (deltaQuota<0){//间隔时间太长,溢出
            this.leftQuota=capacity;
            this.leakingTs = nowTs;
            return;
        }
        if (deltaQuota<1){//说明漏的时间不够
            return;
        }
        this.leakingTs = nowTs;
        this.leftQuota = this.leftQuota + deltaQuota;
        if (this.leftQuota>this.capacity){
            this.leftQuota =this.capacity;
        }

    }


    public Boolean water(int quota){
        makeSpace();
        if (leftQuota >=quota){//表示量充足
            leftQuota =  leftQuota-quota;
            return true;
        }
        //剩余量不够
        return false;
    }
}
